package com.power.using.sharlockchat.service;

import android.app.Dialog;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.power.using.sharlockchat.bean.VersionInfo;
import com.power.using.sharlockchat.http.HttpApi;
import com.power.using.sharlockchat.http.Request;
import com.power.using.sharlockchat.utils.HttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

public class DownLoadService extends Service {
    public static boolean isRunnning = false;

    private HomeListener mHomeListener;
    Handler mHandler;
    Dialog mDialog;


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Log.i("TAG", "onCreateservice");
        super.onCreate();
        mHomeListener = new HomeListener(getApplicationContext());
        mHomeListener.setOnHomePressedListener(new HomeListener.OnHomePressedListener() {
            @Override
            public void onHomePressed() {
                if (mDialog != null) {
                    mDialog.cancel();
                }
            }

            @Override
            public void onHomeLongPressed() {
                if (mDialog != null) {
                    mDialog.cancel();
                }
            }
        });
        mHomeListener.startWatch();
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                int msgid = msg.what;
                switch (msgid) {
                    case HttpUtils.version_msg:// 网络访问成功  handler进行版本号比较
                        final VersionInfo entity = (VersionInfo) msg.getData().getSerializable("version");

                        Log.e("nowversion", entity.getVERSIONCODE());
                        try {
                            PackageManager manager = getPackageManager();
                            String packageName = getPackageName();
                            PackageInfo packageInfo;
                            packageInfo = manager.getPackageInfo(packageName, 0);
                            Log.e("versioncode", packageInfo.versionCode + "");
                            //  如果版本号大于现在的版本 就下载
                            if (packageInfo.versionCode < Integer.valueOf(entity.getVERSIONCODE())) {

                                //　如果sd卡有已经下载好的  apk 那就直接安装  ，不用下载.
                                String strPath = Environment
                                        .getExternalStorageDirectory()
                                        .getAbsolutePath() + "/" + entity.getVERSIONCODE() + "new.apk";
                                final File strFile = new File(strPath);

                                Log.e("strPath", strPath + true);
                                //  如果文件存在
                                if (strFile.exists()) {
                                    Log.e("cunzai", " 存在" + strFile.getAbsolutePath());
                                    Intent intent = new Intent();
                                    intent.putExtra("file", strFile.getAbsolutePath());
                                    intent.setAction("com.sibosi.yzdsupervisep.service.DownLoadService");
                                    sendBroadcast(intent);
                                    stopSelf();
                                }
                                // 如果文件不存在
                                HttpUtils.requestDownloadFile(getApplicationContext(), HttpApi.DOWN_UPDATE, "", entity.getVERSIONCODE() + "new.apk", new Request() {


                                    @Override
                                    public void successFile(File file) {
                                        super.successFile(file);
                                        Log.e("file", file.getAbsolutePath());

                                        Intent intent = new Intent();
                                        intent.putExtra("file", file.getAbsolutePath());
                                        intent.setAction("com.sibosi.yzdsupervisep.service.DownLoadService");
                                        sendBroadcast(intent);
                                        stopSelf();


                                    }

                                    @Override
                                    public void error(String error) {
                                        super.error(error);
                                    }
                                });




                            } else {
                                // 说明当前是最新版本  并且更新成功
                                //那么就删除原来的更新文件
                                String strPath = Environment
                                        .getExternalStorageDirectory()
                                        .getAbsolutePath() + "/" + entity.getVERSIONCODE() + "new.apk";
                                final File strFile = new File(strPath);

                                Log.e("strPath", strPath + true);
                                //  如果文件存在
                                if (strFile.exists()) {
                                    strFile.delete();
                                    Log.e("shanchuchenggong", "删除成功");
                                    stopSelf();
                                } else {
                                    Log.e("shanchuchenggong", "yijing删除成功");
                                    return;
                                }
                                stopSelf();
                            }
                        } catch (PackageManager.NameNotFoundException e) {
                            e.printStackTrace();
                        }
                        break;

                    default:
                        break;


                }
            }
        };


    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("测试", "onStartservice");
        isRunnning = true;
        //获取版本信息的网络请求  如果wifi可用 并且 是链接状态
//        if (NetworkUtils.isWifiAvailable(ActivityManager.getInstance().currentActivity())&& NetworkUtils.isConnected(ActivityManager.getInstance().currentActivity()))
        HttpUtils.requestGet(getApplicationContext(), HttpApi.GETVERINFO, new Request()

        {
            @Override
            public void success(String jsonStr) {
                super.success(jsonStr);
                //　获取版本号成功
                Log.e("json", jsonStr);
//                VersionInfo  mVersionInfo = new Gson().fromJson(jsonStr,VersionInfo.class);

                try {
                    JSONObject jsonObject = new JSONObject(jsonStr);
                    String versionname = jsonObject.optString("VERSIONNAME");
                    String versioncode = jsonObject.optString("VERSIONCODE");

                    VersionInfo mVersionInfo = new VersionInfo(versionname, versioncode);
                    Log.e("mversioninfo", mVersionInfo.getVERSIONCODE() + mVersionInfo.getVERSIONNAME() + mVersionInfo.getID());
                    Message message = new Message();
                    message.what = HttpUtils.version_msg;
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("version", mVersionInfo);
                    message.setData(bundle);
                    mHandler.sendMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void error(String error) {
                super.error(error);
            }
        });

        return START_STICKY;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isRunnning = false;
        mHomeListener.stopWatch();
    }
}
